package xworker.gluon.attach.audio;

import com.gluonhq.attach.audio.Audio;
import com.gluonhq.attach.audio.AudioService;
import org.xmeta.ActionContext;
import org.xmeta.Thing;

import java.net.URL;
import java.util.List;

public class AudioActions {
    public static void create(ActionContext actionContext){
        Thing self = actionContext.getObject("self");
        String type = self.getString("type");
        boolean looping = self.getBoolean("looping");
        URL url = self.doAction("getUrl", actionContext);

        AudioService audioService = AudioService.create().orElse(null);
        if(audioService != null){
            Audio audio = "sound".equals(type) ? audioService.loadSound(url).orElse(null) : audioService.loadMusic(url).orElse(null);
            if(audio != null){
                if(looping){
                    audio.setLooping(looping);
                }
                if(self.valueExists("volume")){
                    audio.setVolume(self.getDouble("volume"));
                }
                if(self.getBoolean("play")){
                    audio.play();
                }
            }

            actionContext.g().put(self.getMetadata().getName(), audio);
        }
    }

    public static Audio load(ActionContext actionContext){
        Thing self = actionContext.getObject("self");
        String type = self.doAction("getType", actionContext);
        URL url = self.doAction("getUrl", actionContext);
        AudioService audioService = AudioService.create().orElse(null);
        if(audioService != null){
            return "sound".equals(type) ? audioService.loadSound(url).orElse(null) : audioService.loadMusic(url).orElse(null);
        }

        return null;
    }

    public static void play(ActionContext actionContext){
        Thing self = actionContext.getObject("self");
        Audio audio = self.doAction("getAudio", actionContext);
        if(audio != null){
            audio.play();
        }
    }

    public static void pause(ActionContext actionContext){
        Thing self = actionContext.getObject("self");
        Audio audio = self.doAction("getAudio", actionContext);
        if(audio != null){
            audio.pause();
        }
    }

    public static void stop(ActionContext actionContext){
        Thing self = actionContext.getObject("self");
        Audio audio = self.doAction("getAudio", actionContext);
        if(audio != null){
            audio.stop();
        }
    }

    public static void dispose(ActionContext actionContext){
        Thing self = actionContext.getObject("self");
        List<String> audios = self.doAction("getAudios", actionContext);
        for(String au : audios){
            Audio audio = actionContext.getObject(au);
            if(audio != null){
                audio.dispose();
            }
        }
    }
}
